package com.woniuxy.ams.shiro.filter;

import com.woniuxy.ams.shiro.token.JwtToken;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

/**
 * 过滤器，继承BasicHttpAuthenticationFilter
 * 不需要配置类注解，因为，这个filter直接写完是没有作用的！
 * 需要把它通过配置类的形式，注入到SecurityManager中！
 *
 * @author fyx
 */
public class ShiroFilter extends BasicHttpAuthenticationFilter {
    private static final String AUTH_HEADER = "authorization";

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        request.getRequestDispatcher("/status/401").forward(request, response);
        return false;
    }

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        if (isLoginAttempt(request, response)) {
            return executeLogin(request, response);
        }
        return false;
    }

    @Override
    protected boolean isLoginAttempt(ServletRequest request, ServletResponse response) {
        String authHeader = ((HttpServletRequest) request).getHeader(AUTH_HEADER);
        return authHeader != null;
    }

    /**
     * 真正执行登录的地方
     *
     * @param request  传入的request
     * @param response 传出的response
     * @return 是否成功
     */
    @Override
    protected boolean executeLogin(ServletRequest request, ServletResponse response) {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        // 从请求头中获取，authorization，对象 有这个对象则表示可以认证
        String authorization = httpServletRequest.getHeader(AUTH_HEADER);
        //json转对象
        try {
            Subject subject = SecurityUtils.getSubject();
            subject.login(new JwtToken(authorization));
        } catch (Exception e) {
            return false;
        }
        return true;
    }
}
